#include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
#include <drv/pin.h>
#include <drv/uart.h>
#include "sys_console.h"


char num2ascii[16]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};

int32_t console_init(sys_console_t *handle)
{
    int32_t ret = 0;

    csi_uart_config_t tUartConfig;

    csi_pin_set_mux(handle->tx.pin, handle->tx.func);
    csi_pin_set_mux(handle->rx.pin, handle->rx.func);
    csi_pin_pull_mode(handle->rx.pin, GPIO_PULLUP);

    tUartConfig.byParity = UART_PARITY_NONE;		//no parity
    tUartConfig.wBaudRate = handle->baudrate;		//115200
    tUartConfig.wInt = UART_INTSRC_NONE;			//no interrupt		
    tUartConfig.byRxMode = UART_RX_MODE_POLL;
    tUartConfig.byTxMode = UART_TX_MODE_POLL;

    ret = csi_uart_init(handle->uart, &tUartConfig);

    if(ret < 0)
        return -1;

    csi_uart_start(handle->uart, UART_FUNC_RX_TX);

    return ret;
}

__attribute ((weak))int fputc(int ch, FILE *stream)
{
    (void)stream;

//    if (ch == '\n') {
//        csi_uart_putc(console.uart, (uint8_t)'\r');
//    }

    csi_uart_putc(console.uart, (uint8_t)ch);

    return 0;
}

__attribute ((weak))int fgetc(FILE *stream)
{
    uint8_t ch;
    (void)stream;

    ch = csi_uart_getc(console.uart);

    return (int)ch;
}


void console_log_string(char *data)
{
    while(*data != '\0')
    {
        csi_uart_putc(console.uart, *data);
        data++;
    }
}

void console_log_string_num(char *data,uint32_t num)
{
  //return;
    char numstring[13];
    uint8_t j=0;
    uint32_t pound = 1000000000;
    console_log_string(data);
    if(num)
    {
        for(uint8_t i=0;i<10;i++)
        {
            if(j == 0)
            {
                if(num/pound)
                {
                    numstring[j++] = num2ascii[num/pound];
                }
            }
            else
            {
                numstring[j++] = num2ascii[num/pound];
            }
            num%=pound;
            pound/=10;
        }
    }
    else
    {
    numstring[j++] = num2ascii[0];
    }
    numstring[j++] = '\n';
    numstring[j++] = '\0';
    console_log_string(numstring);

}
void console_log_num_byte(uint8_t *num_byte,uint32_t len)
{
    char numstring[len*3+3];
    uint8_t num;
    uint32_t o_len=0;
    if(len)
    {
        for(uint32_t i=0;i<len;i++)
        {
            num = *(num_byte+i);
            num >>= 4;
            numstring[o_len++] = num2ascii[num&0xf];
            
            num = *(num_byte+i);
            numstring[o_len++] = num2ascii[num&0xf];

            numstring[o_len++] = ' ';
        }
    }
    else
    {
        numstring[o_len++] = num2ascii[0];
    }
    numstring[o_len++] = '\n';
    numstring[o_len++] = '\0';
    console_log_string(numstring);
}